package com.bitrate.dagger.server.websocket.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.Tio;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.starter.TioWebSocketServerBootstrap;

import com.bitrate.dagger.sdk.websocket.dto.WebSocketPushDTO;
import com.bitrate.dagger.server.websocket.cache.LocalCache;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;

/**
 * 接受发布相关Controller
 */
@RestController
@RequestMapping("/websocket-api")
public class WebSocketPushController {

	@Autowired
	private TioWebSocketServerBootstrap serverBootstrap;

	@PostMapping("push")
	public String push(@RequestBody WebSocketPushDTO pushDto) {
		String commonKey = pushDto.getCommonKey();
		if (!LocalCache.contains(commonKey)) {
			return "FAIL";
		}
		List<String> channelArr = pushDto.getChannelArr();
		if (CollUtil.isEmpty(channelArr)) {
			return "FAIL";
		}
		// 并行处理
		String pushText = JSONUtil.toJsonStr(pushDto.getRequest());
		channelArr.parallelStream().forEach(channel -> {
			Tio.sendToUser(serverBootstrap.getServerGroupContext(), channel, WsResponse.fromText(pushText, "utf-8"));
		});
		return "SUCCESS";
	}
}
